<!-- 马佳乐 大文件上传 2023年8月16日13点33分 -->
<template>
    <div>
        <el-row>
           <el-col :span="2">
               <el-button type="primary" plain style="margin-left:10px" @click="uploadFile" icon="el-icon-upload2">上传</el-button>
           </el-col>
            <!-- <el-input placeholder="请输入内容" v-model="fileManagerName" class="input-with-select" style="width: 300px">
                <el-button slot="append" icon="el-icon-search" @click="queryFile()"></el-button>
            </el-input> -->
        </el-row>
        <el-drawer title="上传文件" :visible.sync="visible" size="38%">
            <uploader  :autoStart="false" :options="options" :file-status-text="statusText"
                       class="uploader-example" @file-complete="fileComplete" @complete="complete"
                       @file-success="fileSuccess" @files-added="filesAdded">
                <uploader-unsupport></uploader-unsupport>
                <uploader-drop>
                    <p>将文件拖放到此处以上传</p>
                    <uploader-btn>选择文件</uploader-btn>
                    <uploader-btn :attrs="attrs">选择图片</uploader-btn>
                    <uploader-btn :directory="true">选择文件夹</uploader-btn>
                </uploader-drop>
                <!-- <uploader-list></uploader-list> -->
                <uploader-files> </uploader-files>
            </uploader>
            <br />
            <el-button @click="allStart()" :disabled="disabled">全部开始</el-button>
            <el-button @click="allStop()" style="margin-left: 4px">全部暂停</el-button>
            <el-button @click="allRemove()" style="margin-left: 4px">全部移除</el-button>
        </el-drawer>
  
        <el-col style="margin-top: 20px">
            <el-table :data="fileArray" style="width: 100%">
                <el-table-column prop="fileManagerName" label="文件名" >
                </el-table-column>
                <el-table-column prop="size" label="大小(MB)" >
                </el-table-column>
                <el-table-column prop="nickName" label="上传人">
                </el-table-column>
                <el-table-column prop="createTime" label="创建日期">
                </el-table-column>
                <el-table-column label="操作" align="center">
                    <template slot-scope="scope">
                      <el-button type="primary" size="small" style="background:none;border:0px"><span style="color:#409EFF;" @click="download(scope.row.fileManagerId,scope.row.fileManagerName)"><i class="el-icon-share"></i>下载</span></el-button>
                        <!-- <el-button type="primary" @click="LargeFilesDownload(scope.row.fileManagerId,scope.row.fileManagerName)">大文件下载</el-button> -->
                        <el-button type="primary" size="small" style="background:none;border:0px"><span style="color:#409EFF;" @click="updatedelete(scope.row.fileManagerId)"><i class="el-icon-delete"></i>删除</span></el-button>
                    </template>
                </el-table-column>
            </el-table>
            <el-pagination
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :current-page="page.pageNum"
                :page-sizes="[10, 20, 30, 40]"
                :page-size="page.pageSize"
                layout="total, sizes, prev, pager, next, jumper"
                :total="page.total">
            </el-pagination>
        </el-col>
  
    </div>
  
  </template>
  
  <script>
  import axios from 'axios'
  import SparkMD5 from 'spark-md5'
  // import storage from 'store'
  
  export default {
    name: 'cloudDiskManagement.vue',
    data () {
      return {
        user: JSON.parse(localStorage.getItem("user")),
        page: {
          total: 0, // 数据总条数
          pageNum: 1, // 当前页
          pageSize: 10// 每页条数
        },
        fileArray: [], // 查询所有文件
        fileManagerName: '', // 模糊查询文件名称
        visible: false,
        skip: false,
        options: {
          target: `${axios.defaults.baseURL}/upload/chunk`,
          // 开启服务端分片校验功能
          testChunks: true,
          parseTimeRemaining: function (timeRemaining, parsedTimeRemaining) {
            return parsedTimeRemaining
              .replace(/\syears?/, '年')
              .replace(/\days?/, '天')
              .replace(/\shours?/, '小时')
              .replace(/\sminutes?/, '分钟')
              .replace(/\sseconds?/, '秒')
          },
          // 服务器分片校验函数
          checkChunkUploadedByResponse: (chunk, message) => {
            const result = JSON.parse(message)
            if (result.data.skipUpload) {
              this.skip = true
              return true
            }
            return (result.data.uploaded || []).indexOf(chunk.offset + 1) >= 0
          }
          // headers: {
          //     // 在header中添加的验证，请根据实际业务来
          //     "Access-Token": storage.get(ACCESS_TOKEN),
          // },
        },
        attrs: {
          accept: 'image/*'
        },
        statusText: {
          success: '上传成功',
          error: '上传出错了',
          uploading: '上传中...',
          paused: '暂停中...',
          waiting: '等待中...',
          cmd5: '计算文件MD5中...'
        },
        fileList: [],
        disabled: true,
        user: JSON.parse(localStorage.getItem("user"))
      }
    },
    watch: {
      fileList (o, n) {
        this.disabled = false
      }
    },
    mounted () {
      this.queryFile()
    },
    methods: {
      // 分片下载
      LargeFilesDownload (fileManagerId, fileManagerName) {
        axios({
          method: 'get',
          url: 'http://127.0.0.1:8201/downloadFile'
        })
      },
      // 普通下载
      download: function (fileManagerId, fileManagerName) {
        axios({
          method: 'get',
          url: '/fileManager/downLoadFile/' + fileManagerId,
          responseType: 'blob'
        }).then(function (response) {
          const content = response.data
          const blob = new Blob([content])
          if ('download' in document.createElement('a')) {
            // 非IE下载
            const elink = document.createElement('a')
            elink.download = fileManagerName
            elink.style.display = 'none'
            elink.href = URL.createObjectURL(blob)
            document.body.appendChild(elink)
            elink.click()
            // 释放URL对象
            URL.revokeObjectURL(elink.href)
            document.body.removeChild(elink)
            alert('下载成功')
          } else {
            navigator.msSaveBlob(blob, fileManagerName)
            alert('下载失败')
          }
        }, function () {
  
        })
      },
      // 用户表逻辑删除
      updatedelete (fileManagerId) {
        this.$confirm('是否删除该用户信息', '提示', {
                confirmButtonClass: '确定',
                cancelButtonText: '取消',
                type: 'waning'
            }).then(() => {
                this.$axios.delete('/fileManager/deleteFileManage', {
                params: {
                    fileManagerId: fileManagerId
                }
              }).then(res => {
                if (res.data.flag) {
                    this.queryFile()
                    this.$message({ message: '删除成功!', type: 'success' })
                } else {
                    this.Mymessage('waning', '删除失败!')
                }
                }).catch(res => {
                this.Mymessage('error', '删除失败,请联系管理员')
                })
            }).catch(() => {
                this.Mymessage('info', '已取消删除')
            })
        },
      // 查询所有文件
      queryFile () {
        this.id = this.user.id
        this.request.get('/fileManager/queryFile', {
          params: {
            id: this.id,
            pageNum: this.page.pageNum,
            pageSize: this.page.pageSize,
            fileManagerName: this.fileManagerName
          }
        }).then(res => {
          if (res.data) {
            this.fileArray = res.data.content
            this.page.total = res.data.totalSize
          }
        })
      },
      handleSizeChange (val) { // 分页
        this.page.pageSize = val
        this.queryFile()
      },
      handleCurrentChange (val) { // 分页
        this.page.pageNum = val
        this.queryFile()
      },
      // 打开弹窗
      uploadFile () {
        this.visible = true
      },
      fileSuccess (rootFile, file, response, chunk) {

        const result = JSON.parse(response)
  
        if (result.success && !this.skip) {
          axios.post('/upload/merge',{
                identifier: file.uniqueIdentifier,
                filename: file.name,
                totalChunks: chunk.offset,
                uploadedBy: this.user.id
                // formdata.set('teacherId', this.user.id)
              }
              // {
              //     headers: { "Access-Token": storage.get(ACCESS_TOKEN) }
              // }
            )
            .then((res) => {
              if (res.data.code==200) {
                this.queryFile()
               this.$message.success('上传成功')
              } else {
                console.log(res)
              }
            })
            .catch(function (error) {
              console.log(error)
            })
        } else {
          console.log('上传成功，不需要合并')
        }
        if (this.skip) {
          this.skip = false
        }
      },
      fileComplete (rootFile) {
        // 一个根文件（文件夹）成功上传完成。
        // console.log("fileComplete", rootFile);
        // console.log("一个根文件（文件夹）成功上传完成。");
      },
      complete () {
        // 上传完毕。
        // console.log("complete");
      },
      filesAdded (file, fileList, event) {
        // console.log(file);
        file.forEach((e) => {
          this.fileList.push(e)
          this.computeMD5(e)
        })
      },
      computeMD5 (file) {
        const fileReader = new FileReader()
        const time = new Date().getTime()
        const blobSlice =
                File.prototype.slice ||
                File.prototype.mozSlice ||
                File.prototype.webkitSlice
        let currentChunk = 0
        const chunkSize = 1024 * 1024
        const chunks = Math.ceil(file.size / chunkSize)
        const spark = new SparkMD5.ArrayBuffer()
        // 文件状态设为"计算MD5"
        file.cmd5 = true // 文件状态为“计算md5...”
        file.pause()
        loadNext()
        fileReader.onload = (e) => {
          spark.append(e.target.result)
          if (currentChunk < chunks) {
            currentChunk++
            loadNext()
            // 实时展示MD5的计算进度
            console.log(
                        `第${currentChunk}分片解析完成, 开始第${
                            currentChunk + 1
                        } / ${chunks}分片解析`
            )
          } else {
            const md5 = spark.end()
            console.log(
                        `MD5计算完毕：${file.name} \nMD5：${md5} \n分片：${chunks} 大小:${
                            file.size
                        } 用时：${new Date().getTime() - time} ms`
            )
            spark.destroy() // 释放缓存
            file.uniqueIdentifier = md5 // 将文件md5赋值给文件唯一标识
            file.cmd5 = false // 取消计算md5状态
            file.resume() // 开始上传
          }
        }
        fileReader.onerror = function () {
          this.error(`文件${file.name}读取出错，请检查该文件`)
          file.cancel()
        }
        function loadNext () {
          const start = currentChunk * chunkSize
          const end =
                    start + chunkSize >= file.size ? file.size : start + chunkSize
          fileReader.readAsArrayBuffer(blobSlice.call(file.file, start, end))
        }
      },
      // 根据登录信息获取文件
      getFileById () {
        this.$axios.get('/fileManager/getFileById' ,{
          params: {
            uploadedBy: this.user.id
          }
        }).then(res => {
          if (!res.data.data) {
            this
          }
        })
      },
      allStart () {
        console.log(this.fileList)
        this.fileList.map((e) => {
          if (e.paused) {
            e.resume()
          }
          return e
        })
      },
      allStop () {
        console.log(this.fileList)
        this.fileList.map((e) => {
          if (!e.paused) {
            e.pause()
          }
          return e
        })
      },
      // allRemove () {
      //   this.fileList.map((e) => {
      //     e.cancel()
      //   })
      //   this.fileList = []
      // },
      Mymessage (type, text) { 
        this.$message({
            showClose: true,
            message: text,
            type: type
        })
        }
    }
  }
  </script>
  
  <style>
  .uploader-example {
    width: 100%;
    padding: 15px;
    margin: 0px auto 0;
    font-size: 12px;
    box-shadow: 0 0 10px rgba(0, 0, 0, 0.4);
    background: #e6e6e6;
  }
  .uploader-example .uploader-btn {
    margin-right: 4px;
  }
  .uploader-example .uploader-list {
    max-height: 440px;
    overflow: auto;
    overflow-x: hidden;
    overflow-y: auto;
  }
  .uploader-example .uploader-file-status {
    width: 24%;
    text-indent: -10px;
  }
  </style>
  